package cj.web.prize.controllers;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.web.prize.dao.PrizeDAO;
import cj.web.prize.dao.PrizeGiftDAO;
import cj.web.prize.dao.PrizeResultDAO;
import cj.web.prize.domain.PrizeGift;
import cj.web.prize.domain.PrizeResult;
import cj.web.utils.GiftRandom;
import cj.web.utils.NetworkUtil;
import cj.web.utils.StringRandom;

@Path("/prize")
public class PrizeController {

	private static Logger logger = Logger.getLogger(PrizeController.class
			.getName());

	@Autowired
	private PrizeResultDAO prizeResultDao;
	@Autowired
	private PrizeDAO prizeDao;
	@Autowired
	private PrizeGiftDAO prizeGiftDao;

	@Get("download")
	public String download() {
		return "/views/wuhanguan/download.vm";
	}

	@Get("share")
	public String share() {
		return "/views/wuhanguan/share.vm";
	}

	@Get("giftPage")
	public String giftPage() {
		return "/views/activity/loading.vm";
	}

	/**
	 * 中间页
	 * 
	 * @return
	 */
	@Get("showGift")
	public String showGift(@Param("deviceId") String deviceId) {
		List<PrizeResult> objs = prizeResultDao.queryByDeviceID(deviceId,
				Constants.Activity.ActivityId_5);
		if (objs != null && objs.size() > 0) {
			// 存在
			return "r:getGiftDetailPage?deviceId=" + deviceId;
		} else {
			// 不存在
			return "r:index?deviceId=" + deviceId;
		}
	}

	/**
	 * 中奖详情页面
	 * 
	 * @return
	 */
	@Get("getGiftDetailPage")
	public String getGiftDetailPage(Model model,
			@Param("deviceId") String deviceId, @Param("first") String first) {
		List<PrizeResult> objs = prizeResultDao.queryByDeviceID(deviceId,
				Constants.Activity.ActivityId_5);

		if (objs != null && objs.size() > 0) {
			PrizeResult obj = objs.get(0);
			if ("0".equals(first)) {
				model.add("first", Constants.returnObj.returnFlag_true);
			} else {
				model.add("first", Constants.returnObj.returnFlag_flase);
			}

			model.add("obj", obj);
		}

		// return "/views/activity/wining.vm";
		return "/views/wuhanguan/whgStatus.vm";
	}

	/**
	 * 抽奖页面
	 * 
	 * @param model
	 * @return
	 */
	@Get("index")
	public String goGiftPage(Model model, @Param("deviceId") String deviceId,
			HttpServletRequest request) {
		if (deviceId == null || "".equals(deviceId)) {
			try {
				deviceId = NetworkUtil.getIpAddress(request);
			} catch (IOException e1) {
				UUID uuid = UUID.randomUUID();
				deviceId = uuid.toString();
			}
		}

		model.add("activeId", Constants.Activity.ActivityId_5);
		model.add("deviceId", deviceId);
		// 是否抽过奖
		List<PrizeResult> objs = prizeResultDao.queryByDeviceID(deviceId,
				Constants.Activity.ActivityId_5);

		if (objs != null && objs.size() > 0) {
			model.add("first", Constants.returnObj.returnFlag_flase);
		} else {
			model.add("first", Constants.returnObj.returnFlag_true);
		}
		// return "/views/activity/turnplate.vm";
		return "/views/wuhanguan/whgLottery.vm";
	}

	/**
	 * 抽奖
	 * 
	 * @param model
	 * @param deviceId
	 * @param activeId
	 * @return
	 */
	@Get("goGiftByDeviceId")
	public String goGiftByDeviceId(Model model,
			@Param("deviceId") String deviceId, @Param("activeId") int activeId) {
		JSONObject jo = new JSONObject();
		String nowdate = DateUtils.getNowTime();// 当前时间
		int activeObj = prizeDao.queryByIdAndDate(activeId,
				nowdate);

		if (activeObj == 0) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_true);
			jo.put("code", Constants.Activity.code_A01);
			return "@" + jo.toString();
		}

		// 是否抽过奖
		List<PrizeResult> objs = prizeResultDao.queryByDeviceID(deviceId,
				Constants.Activity.ActivityId_5);

		if (objs != null && objs.size() > 0) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_true);
			jo.put("code", Constants.Activity.code_A02);
			jo.put("first", Constants.returnObj.returnFlag_flase);
			return "@" + jo.toString();
		}

		Map rep = returnGiftRandom(activeId);

		double rate0 = Double.parseDouble(rep.get("rate0").toString());
		double rate1 = Double.parseDouble(rep.get("rate1").toString());
		// double rate2 = Double.parseDouble(rep.get("rate2").toString());
		// double rate3 = Double.parseDouble(rep.get("rate3").toString());
		// double rate4 = Double.parseDouble(rep.get("rate4").toString());
		// double rate5 = Double.parseDouble(rep.get("rate5").toString());
		// double rate6 = Double.parseDouble(rep.get("rate6").toString());

		try {
			// String percentageRandom =
			// String.valueOf(GiftRandom.PercentageRandom(rate0,rate1,rate2,rate3,rate4,rate5,rate6));
			String percentageRandom = String.valueOf(GiftRandom.PercentageRandom(rate0, rate1));
			PrizeResult obj = new PrizeResult();
			obj.setDeviceID(deviceId);
			obj.setActiveID(activeId);

			if (Constants.Activity.Status_3.equals(percentageRandom)) {
				obj.setStatus(-1);
			} else {
				obj.setStatus(Constants.Activity.Status_0);
			}

			obj.setPhone(StringRandom.getStringRandom(8));
			obj.setRemark(percentageRandom);

			prizeResultDao.create(obj);

			prizeGiftDao.updateCountByActiveId(activeId, percentageRandom);

			jo.put("returnFlag", Constants.returnObj.returnFlag_true);
			jo.put("code", Constants.Activity.code_A00);
			jo.put("gift", obj.getRemark());
			jo.put("token", obj.getPhone());
			jo.put("first", Constants.returnObj.returnFlag_true);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}

		return "@" + jo.toString();
	}

	/**
	 * 返回奖品概率
	 * 
	 * @param activeId
	 * @return
	 */
	private Map returnGiftRandom(int activeId) {
		Map rep = new HashMap();
		List<PrizeGift> agpList = prizeGiftDao.queryByActiveId(activeId);
		int i = 0;
		for (PrizeGift obj : agpList) {
			if ("0".equals(obj.getCount())) {
				rep.put("rate" + i++, "0");
			} else {
				// 原始概率
				double probability = Double.parseDouble(obj.getProbability());
				// 扣减的概率 = 原始概率/每日发放总量
				double ss = probability / Integer.valueOf(obj.getDayCount());
				// 每日剩余量 = 每日发放总量-每日发放量
				int sycount = Integer.valueOf(obj.getDayCount())
						- Integer.valueOf(obj.getCount());
				// 新概率 = 原始概率-扣减的概率*每日剩余量
				probability = probability - ss * sycount;

				rep.put("rate" + i++, probability);
			}

		}

		return rep;
	}
}